﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using FotoAnotSharp.Gate;
using FotoAnotSharp.Anotator;
using System.Xml;

namespace FotoAnotSharp
{
    /// <summary>
    /// This class is the center of program.
    /// Creating GUI and it is simply code without data.
    /// </summary>
    public partial class GateDemo : Form
    {
        public GateDemo()
        {
            InitializeComponent();

            Icon = SystemIcons.Application;

            RenewText();

            Load += new EventHandler(GateDemo_Load);
            FormClosing += new FormClosingEventHandler(GateDemo_FormClosing);
        }

        void GateDemo_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult res = MessageBox.Show("Přejete si uložit soubor?", "Ukončit", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            switch (res)
            { 
                case System.Windows.Forms.DialogResult.Yes:
                    SaveFile(false);
                    break;
                case System.Windows.Forms.DialogResult.No:
                    return;
                case System.Windows.Forms.DialogResult.Cancel:
                    e.Cancel = true;
                    return;
            }
        }

        public void RenewText()
        {
            Text = string.Format("Foto anot # - {0}", string.IsNullOrEmpty(mFilePath) ? "Nový soubor" : string.Format("\"{0}\"", mFilePath));
        }

        /// <summary>
        ///  load hierarchy from gate.owl.xml to gateAnotationComponent
        /// </summary>
        void GateDemo_Load(object sender, EventArgs e)
        {
            GraphicalObjectHiearchy h;
            GateReader l = new GateReader();
            l.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "gate.owl.xml"), out h);
            gateAnotaionComponent1.LoadGate(h);
        }

        /// <summary>
        /// load picture or anotated picture from file
        /// </summary>
        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadFile(null);
        }
        
        private void uložitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFile(false);
        }
        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFile(true);
        }

        private string mFilePath = null;

        const string FILE_EXT_XML = "XML soubory | *.xml";

        void LoadFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                using (OpenFileDialog d = new OpenFileDialog())
                {
                    d.Filter = FILE_EXT_XML;
                    if (d.ShowDialog() != DialogResult.OK)
                        return;

                    filePath = d.FileName;
                }
            }

            GateAnotatedFile file = GateAnotatedFile.Load(filePath);
            if (file == null)
                return;
            gateAnotaionComponent1.LoadFile(file);
            mFilePath = filePath;

            RenewText();
        }

        void SaveFile(bool forceAs)
        {
            string file = mFilePath;
            if (forceAs || string.IsNullOrEmpty(file))
            {
                using (SaveFileDialog d = new SaveFileDialog())
                {
                    d.Filter = FILE_EXT_XML;
                    if (d.ShowDialog() != DialogResult.OK)
                        return;

                    file = d.FileName;
                }
            }

            GateAnotatedFile.Save(gateAnotaionComponent1.GetSaveFile(), file);
            mFilePath = file;
            RenewText();
        }

        private void znovuNačístToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Přejete si skutečně znovu načíst aktuální soubor?", "Poslední změny budou ztraceny", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.Yes)
                return;

            LoadFile(mFilePath);
        }

        private void ukončitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Image image = gateAnotaionComponent1.AnotatedImage;

                if (image == null)
                {
                    MessageBox.Show("Nelze exportovat bez dodaného pozadí", "Nelze pokračovat", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                IEnumerable<AnotPolygonTree> composTrees = gateAnotaionComponent1.GenerateCompositionTrees();
                IEnumerable<GateAnotaionComponent.AnotatedObject> objects = gateAnotaionComponent1.AnotatedObjects;

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.CloseOutput = true;
                settings.OmitXmlDeclaration = false;
                settings.Indent = true;
                settings.NewLineOnAttributes = false;

                using (SaveFileDialog d = new SaveFileDialog())
                {
                    d.Filter = "SVG soubory | *.svg";
                    if (d.ShowDialog() != DialogResult.OK)
                        return;

                    using (XmlWriter fs = XmlWriter.Create(d.FileName, settings))
                    {
                        XmlOutputWriter.Write(composTrees, objects, image, fs);
                    }

                    Debug.WriteLine("Export done...");
                    MessageBox.Show("Export byl úpěšně dokončen", "Export dokončen", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception er)
            {
                Debug.WriteLine("Export error " + er.Message + er.StackTrace);
                MessageBox.Show("Při exportu došlo k chybě " + er.Message, "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        

        private void oProgramuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm form = new AboutForm();
            form.ShowDialog();
        }
        
    }
}
